package com.aiyige.page.learn;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.aiyige.R;
import com.aiyige.base.BaseFragment;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.apiengine.OrderEngine;
import com.aiyige.base.eventbus.EventRefreshLearnPageBanner;
import com.aiyige.base.eventbus.EventSelectInterest;
import com.aiyige.base.eventbus.EventSelectRegion;
import com.aiyige.base.eventbus.EventTapBottomItemRefresh;
import com.aiyige.model.Page;
import com.aiyige.model.moment.entity.Moment;
import com.aiyige.page.learn.adapter.LearnDataAdapter;
import com.aiyige.page.selectinterest.util.InterestUtil;
import com.aiyige.utils.widget.CommonDataView;
import com.alibaba.fastjson.JSON;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.ResponseBody;
import retrofit2.Call;


public class LearnDataPage extends BaseFragment implements CommonDataView.RetrofitStub {

    @BindView(R.id.cdv)
    CommonDataView cdv;
    Unbinder unbinder;
    LearnDataAdapter learnDataAdapter;
    int subjectIndex;
    Handler mainHandler;

    public LearnDataPage() {

    }

    public int getSubjectIndex() {
        return subjectIndex;
    }

    public void setSubjectIndex(int subjectIndex) {
        this.subjectIndex = subjectIndex;
    }

    public static LearnDataPage newInstance(int subjectIndex) {
        LearnDataPage fragment = new LearnDataPage();
        fragment.setAutoRegisterEventBus(true);
        fragment.setSubjectIndex(subjectIndex);
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.page_learn_data, container, false);
        unbinder = ButterKnife.bind(this, view);
        mainHandler = new Handler(Looper.getMainLooper());
        learnDataAdapter = new LearnDataAdapter();
        cdv.config(learnDataAdapter, this);
        cdv.setActionCallback(new CommonDataView.UserActionCallback() {
            @Override
            public void onUserRefresh() {
                EventBus.getDefault().post(new EventRefreshLearnPageBanner());
            }

            @Override
            public void onUserLoadMore() {

            }
        });
        cdv.setErrorHandler(new CommonDataView.ErrorHandler() {
            @Override
            public void onResponseError(String errorMsg) {
                EventBus.getDefault().post(EventTapBottomItemRefresh.newBuilder()
                        .itemType(EventTapBottomItemRefresh.ITEM_TYPE_FIND)
                        .actionType(EventTapBottomItemRefresh.ACTION_TYPE_REFRESH_FAILED)
                        .build());
            }

            @Override
            public void onNetError(String errorMsg) {
                EventBus.getDefault().post(EventTapBottomItemRefresh.newBuilder()
                        .itemType(EventTapBottomItemRefresh.ITEM_TYPE_FIND)
                        .actionType(EventTapBottomItemRefresh.ACTION_TYPE_REFRESH_FAILED)
                        .build());
            }
        });
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    protected void initData() {
        cdv.doRefreshRequest();
    }

    @Override
    public Call<ResponseBody> call(long currentPage) {
        switch (subjectIndex) {
            case Moment.SUBJECT_VIDEO_COURSE_INDEX:
                return ApiManager.getService().learnMoment(OrderEngine.LATEST, 20, currentPage, Arrays.asList(Moment.SUBJECT_VIDEO_COURSE), InterestUtil.getInterestId());
            case Moment.SUBJECT_MAJOR_COURSE_INDEX:
                return ApiManager.getService().learnMoment(OrderEngine.LATEST, 20, currentPage, Arrays.asList(Moment.SUBJECT_MAJOR_COURSE), InterestUtil.getInterestId(), 1);
            case Moment.SUBJECT_TRAINING_COURSE_INDEX:
                return ApiManager.getService().learnMoment(OrderEngine.LATEST, 20, currentPage, Arrays.asList(Moment.SUBJECT_TRAINING_COURSE), InterestUtil.getInterestId(), 1);
            case Moment.SUBJECT_TRAINING_CARD_INDEX:
                return ApiManager.getService().learnMoment(OrderEngine.LATEST, 20, currentPage, Arrays.asList(Moment.SUBJECT_TRAINING_CARD), InterestUtil.getInterestId(), 1);
            default:
                return null;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventSelectRegion(EventSelectRegion event) {
        cdv.doRefreshRequest();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventSelectInterest(EventSelectInterest event) {
        cdv.doRefreshRequest();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventTapBottomItemRefresh event) {
        if (isVisible()
                && event.getItemType() == EventTapBottomItemRefresh.ITEM_TYPE_FIND
                && event.getActionType() == EventTapBottomItemRefresh.ACTION_TYPE_START_REFRESH
                && event.getPageType() == subjectIndex) {
            cdv.backToTop(false);
            cdv.showRefreshing();
            mainHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    cdv.doRefreshRequest();
                }
            }, 1000);
        }
    }

    @Override
    public CommonDataView.HandleResult handleResponse(String respJson, List resultList) {
        try {
            Page page = JSON.parseObject(respJson, Page.class);
            List<Moment> momentList = new LinkedList<>();
            if (!TextUtils.isEmpty(page.getContent())) {
                momentList.addAll(JSON.parseArray(page.getContent(), Moment.class));
            }
            for (Moment moment : momentList) {
                resultList.add(new Moment(moment));
            }
            EventBus.getDefault().post(EventTapBottomItemRefresh.newBuilder()
                    .itemType(EventTapBottomItemRefresh.ITEM_TYPE_FIND)
                    .actionType(EventTapBottomItemRefresh.ACTION_TYPE_REFRESH_SUCCEED)
                    .build());
            return new CommonDataView.HandleResult(page.isLast());
        } catch (Exception e) {
            return new CommonDataView.HandleResult(e.getMessage());
        }
    }
}
